import { signalPeerData } from './wss'
import Peer from 'simple-peer'
import store from '@/store/index'
import { setUserStream, setMediaStatus } from '@/store/actions'

let localStream = null

/* 是否是前置摄像头 */
let selectCameraBack = false

export const getDevices = () => {
  if (!navigator.mediaDevices) {
    return Promise.reject('设备不可用')
  }
  navigator.mediaDevices.enumerateDevices()
    .then((devices) => {
      console.log('设备', devices)
    })
    .catch((err) => {
      console.log(err.name + ': ' + err.message)
    })
}

/**
 * 获取本地的媒体流
 */
export const getLocalPreview = () => {
  if (!navigator.mediaDevices) {
    return Promise.reject('设备不可用')
  }
  if (localStream) {
    return localStream
  }
  return localStream || navigator.mediaDevices.getUserMedia({
    audio: true,
    video: {
      facingMode: selectCameraBack ? 'user' : 'environment'
    }
  })
    .then(stream => {
      localStream = stream
      localStream.getAudioTracks()[ 0 ].enabled = store.getState().openAudio
      localStream.getVideoTracks()[ 0 ].enabled = store.getState().openCamera
      store.dispatch(setUserStream({
        userId: store.getState().userId,
        stream: localStream
      }))
      return stream
    })
    .catch(err => {
      console.log(err)
      return Promise.reject(err)
    })
}

const peers = {}

/**
 * 准备webRTC连接
 * @param {String} connectUserId 需要和谁连接
 * @param {Boolean} isInitiator 是否为发起方
 */
export const prepareNewPeerConnection = (connectUserId, isInitiator) => {
  /* 实例化对等连接对象 */
  peers[ connectUserId ] = new Peer({
    initiator: isInitiator,
    stream: localStream,
    config: {
      iceServers: [
        {
          urls: 'stun:stun1.l.google.com:19302',
        },
      ]
    },
  })
  peers[ connectUserId ].on('signal', data => {
    signalPeerData({
      signal: data,
      connectUserId
    })
  })

  /* 获取媒体流 */
  peers[ connectUserId ].on('stream', (stream) => {
    console.log(connectUserId, '媒体流')
    store.dispatch(setUserStream({
      userId: connectUserId,
      stream
    }))
  })
}

/**
 * 保存接收方的信令数据
 */
export const handleSinglingData = (data) => {
  console.log('接收到webETC连接申请', data)
  const { connectUserId, signal } = data

  peers[ connectUserId ].signal(signal)
}

/**
 * 切换音频
 */
export const toggleAudio = (val) => {
  localStream.getAudioTracks()[ 0 ].enabled = val
  console.log(localStream.getAudioTracks())
  store.dispatch(setMediaStatus({
    openAudio: val
  }))
}

/**
 * 切换视频
 */
export const toggleVideo = (val) => {
  localStream.getVideoTracks()[ 0 ].enabled = val
  store.dispatch(setMediaStatus({
    openCamera: val
  }))
  /* 刷新下user的streamID，触发响应式刷新 */
  store.dispatch(setUserStream({
    userId: store.getState().userId,
    stream: localStream
  }))
}

/**
 * 切换前后置摄像头
 */
export const switchCamera = () => {
  selectCameraBack = !selectCameraBack
  /* 需要先把原来的轨道停下来，否则重新切换旧轨道会导致轨道无效 */
  localStream.getTracks().forEach(track => track.stop())
  localStream = null
  getLocalPreview()
}

/**
 * 切换共享屏幕和摄像头
 */
export const changePeerStream = (stream = localStream) => {
  /* 遍历所有对等连接对象，进行媒体轨道替换 */
  for (const key in peers) {
    const peerTracks = peers[ key ].streams[ 0 ].getTracks()
    const streamTracks = stream.getTracks()

    for (const index in peerTracks) {
      for (const index2 in streamTracks) {
        /* 如果两个轨道媒体类型相同，则替换 */
        if (peerTracks[ index ].kind === streamTracks[ index2 ].kind) {
          peers[ key ].replaceTrack(
            peerTracks[ index ],
            streamTracks[ index2 ],
            peers[ key ].streams[ 0 ]
          )
        }
      }
    }
  }
}
